package cn.huanzi.qch.baseadmin.util;

import net.bytebuddy.implementation.bytecode.assign.TypeCasting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.expression.Lists;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.util.*;

/**
 * @author dimples_yj
 * @since 2020-10-10
 */
public class FileUploadUtil {


    /**
     * 文件上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static Map<String, String> fileUpload(MultipartFile file) throws IOException {

        String savePath = "D:/upload";
        List<String> list = Arrays.asList(".jpg", ".jpeg", ".png");
        // 原名字
        String originalFilename = file.getOriginalFilename();
        String extName = originalFilename.substring(file.getOriginalFilename().lastIndexOf("."));
        if (list.contains(extName)) {
            savePath = savePath + File.separator + LocalDate.now().getYear();
            String accessPath = "/upload/" + LocalDate.now().getYear() + "/";
            File fileupload = new File(savePath);
            if (!fileupload.exists()) {
                fileupload.mkdirs();
            }
            // 新文件名字
            String newFileName = UUIDUtil.getUUID() + extName;
            fileupload = new File(savePath, newFileName);
            file.transferTo(fileupload);
            Map<String, String> map = new HashMap<>();
            map.put("accessPath", accessPath + newFileName);
            return map;
        }
        return null;
    }

    /**
     * 文件下载
     *
     * @param fileName
     * @param response
     * @return
     * @throws IOException
     */
    public static MultipartFile fileDownload(String fileName, HttpServletResponse response) throws IOException {

        return null;
    }

}
